package com.example.springbootsecurityjwt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootsecurityjwt.domain.LoginUser;
import com.example.springbootsecurityjwt.domain.User;
import com.example.springbootsecurityjwt.mapper.MenuMapper;
import com.example.springbootsecurityjwt.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @program: SpringBoot-Security-JWT
 * @description: UserDetailsService实现类
 * @author: Coder_Pan
 * @create: 2022-03-22 09:23
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private final UserMapper userMapper;
    private final MenuMapper menuMapper;

    public UserDetailsServiceImpl(UserMapper userMapper, MenuMapper menuMapper) {
        this.userMapper = userMapper;
        this.menuMapper = menuMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User :: getUserName,username);
        //根据传入的username  =>  查询用户信息
        User user = userMapper.selectOne(queryWrapper);
        //如果没有该用户，就抛出异常
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("用户不存在");
        }
        //根据传入的username  =>   查询对应权限信息
//        List<String> list = new ArrayList<>(Arrays.asList("test", "admin"));
        //要通过数据库中存储的权限信息来返回loginUser
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        //封装成UserDetails对象返回
        return new LoginUser(user,list);
    }
}
